# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

import urllib2 as urllib
from xml.dom import minidom
import re
import sys
import traceback

class Querier:
    def __init__(self):
        self.shortName = "lastfm"
        self.longName = "Last.FM"
        self.provides = ['album_front_small', 'album_front_large']

        self.urlFmt = 'http://ws.audioscrobbler.com/2.0/?method=album.search&album=%s&api_key=%s'
        #please don't use this API key for your personal use, 
        #you can apply for one yourself on lastfm web page
        #NOTE!!!
        self.api_key = 'c85a5ed1ffd26bdb198f5c6f42480224'

    def process(self, item):
        ret = []

        album = urllib.quote (item.album.encode("UTF-8"))
        artist = urllib.quote (item.artist.encode("UTF-8"))

        try:
            data = urllib.urlopen(self.urlFmt % (album, self.api_key))
            doc = minidom.parse(data)

            albums = doc.getElementsByTagName('album')
        except Exception, e:
            #print(sys.exc_info())
            traceback.print_exception(*(sys.exc_info()))
            return ret

        for found_album in albums:
            try:
                found_artist = found_album.getElementsByTagName('artist')[0].childNodes[0].nodeValue
                found_album_name = found_album.getElementsByTagName('name')[0].childNodes[0].nodeValue
                contin = False
                if re.search(item.artist, found_artist, re.I):
                    contin = True
                elif( (found_artist == 'Various Artists') and 
                        (re.match(item.album, found_album_name, re.I))):
                    contin = True
                if not contin: 
                    continue

                # get extralarge
                images = found_album.getElementsByTagName('image')
                for image in images[::-1]:
                    #let's change the order, se the bigger is first
                    size = image.attributes['size'].nodeValue
                    if size in ('extralarge', 'large'):
                        if len(image.childNodes) == 0:
                            continue
                        url = image.childNodes[0].nodeValue
                        if 'noimage' not in url:
                            ret.append(url)
            except Exception, e:
                traceback.print_exception(*(sys.exc_info()))
                #print( sys.exc_info() )

        return ret

